<template>
	<view>
		<view class="p15">
			<!-- 基础表单校验 -->
			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" label-position="top" label-width="100%">
				<uni-forms-item>
					<view class="text-center">
						<image :src="valiFormData.head_img" class="head_img" mode="aspectFill" @click="onUpload"></image>
						<uni-icons type="camera-filled" size="30" @click="onUpload"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item label="加入新筑同行交流会" required>
					<uni-data-checkbox v-model="valiFormData.is_join" :localdata="joins" />
				</uni-forms-item>
				<uni-forms-item label="用户名" required name="name">
					<uni-easyinput v-model="valiFormData.name" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="手机号" required name="tell">
					<view class="grid">
						<view class=""><uni-easyinput v-model="valiFormData.tell" placeholder="请输入手机号码"/></view>
						<view class="pl8"><button class="getPhone" open-type="getPhoneNumber" @getphonenumber="getUserPhoneNumber">一键授权</button></view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="在个人主页展示手机号码" required>
					<uni-data-checkbox v-model="valiFormData.show_tell" :localdata="showtells" />
				</uni-forms-item>
				<uni-forms-item label="擅长领域" required>
					<uni-data-checkbox v-model="valiFormData.skill" :localdata="adept" />
				</uni-forms-item>
				<uni-forms-item label="个性签名" name="meta_description">
					<uni-easyinput type="textarea" v-model="valiFormData.meta_description" placeholder="请输入个性签名" />
				</uni-forms-item>
				<uni-forms-item label="个人介绍" name="info">
					<uni-easyinput type="textarea" v-model="valiFormData.info" placeholder="请输入自我介绍" />
				</uni-forms-item>
				<uni-forms-item label="上传图片" name="image">
					<view class="example-body">
						<uni-file-picker limit="9" @select="onSelectImage" @delete="onDeleteImage" :value="valiFormData.fileLists"></uni-file-picker>
					</view>
				</uni-forms-item>
			</uni-forms>
			<button class="default-button" @click="submit('valiForm')">提交</button>
		</view>

		<uni-popup ref="popup" background-color="#fff">
			<uni-row>
				<uni-col :span="8" v-for="item in backImg" :key="item">
					<view><image class="backImg" :src="item" mode="aspectFill" @click="onSelectBackimgInfo(item)" /></view>
				</uni-col>
			</uni-row>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				valiFormData: {
					head_img:'https://xinzhu-1301398555.cos.ap-shanghai.myqcloud.com/wxapp/avatar.png',
					name: '',
					tell: '',
					meta_description: '',
					info: '',
					back_img:'https://gl.xinzhuvip.com/wxapp/1.png',
					fileLists:[]
				},
				images:[],
				joins: [{text: '加入',value: 1}, {text: '拒绝',value: -1}],
				showtells:[{text: '是',value: 1}, {text: '否',value: -1}],
				adept: [
					{text: '设计',value: 1},
					{text: '管理',value: 2},
					{text: '材料',value: 3},
					{text: '施工',value: 4},
					{text: '劳务',value: 5},
					{text: '业务',value: 6},
					{text: '咨询',value: 7},
					{text: '其他',value: 8},
				],
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					tell: {
						rules: [{
							required: true,
							errorMessage: '手机号码不能为空'
						}]
					}
				},
				backImg:[
					'https://gl.xinzhuvip.com/wxapp/1.png',
					'https://gl.xinzhuvip.com/wxapp/2.png',
					'https://gl.xinzhuvip.com/wxapp/3.png',
					'https://gl.xinzhuvip.com/wxapp/4.png',
					'https://gl.xinzhuvip.com/wxapp/5.png',
					'https://gl.xinzhuvip.com/wxapp/6.png',
				]
			}
		},
		onShow() {
			this.onGetUser()
		},
		methods: {
			getUserPhoneNumber(event) {
				let _this = this
				if (event.detail.errMsg != "getPhoneNumber:ok") {
					uni.showToast({title: '取消了授权',icon: 'error',duration: 2000})
					return;
				}
				let code = event.detail.code
				this.$request('/api2/getuserphonenumber','POST',{code:code}).then(res => {
					_this.valiFormData.tell = res.data
					uni.showToast({title: '授权成功',icon: 'success',duration: 2000})
				}).catch(err => {
					console.log(err)
				})
				console.log(event)
			},
			submit(ref) {
				let _this = this
				this.$refs[ref].validate().then(res => {
					// console.log('success', res);
					// _this.onUploadImg()
					_this.onSave()
				}).catch(err => {
					console.log('err', err);
				})
			},
			onSelectBackimgInfo(data){
				this.valiFormData.back_img = data
			},
			onUpload(){
				let _this = this
				uni.chooseImage({
					count: 1, // 默认9，设置图片的数量
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function (res) {
					// 成功选择图片后，获取图片的临时文件路径
						_this.imgToBase64(res.tempFilePaths[0],'avatar')
					}
				});
			},
			onUploadOneImg(e){
				let _this = this
				this.$request_api('applet_api/WxAppOneLoad','POST',{fileurl:e}).then(res => {
					_this.valiFormData.head_img = res.data
				}).catch(err => {
					console.log(err)
				})
			},
			onUploadImg(){
				if(!this.images.length){
					this.onSave()
					return
				}
				let _this = this
				this.$request_api('applet_api/WxAppLoad','POST',{source:this.images}).then(res => {
					res.data.forEach(function(element,index) {
						let obj = {name:element,path:element}
						_this.images[index] = obj
					});
					// _this.onSave()
				}).catch(err => {
					console.log(err)
				})
			},
			onSave(){
				let _this = this
				let img = []
				if(_this.valiFormData.fileLists){
					_this.valiFormData.fileLists.forEach(function(element) {
						if(element.url){
							img.push(element.url)
						}
					});
				}
				
				_this.valiFormData.image = JSON.stringify(img)
				this.$request('/api2/set_user_info','POST',_this.valiFormData).then(res => {
					if(res.code != 0){
						uni.showToast({title: '更新失败',icon: 'error',duration: 2000})
						return;
					}
					uni.showToast({title: '更新成功',icon: 'success',duration: 2000})
					uni.navigateBack({
					    delta: 1 // 默认值是1，表示返回的页面层数
					});
					return;
					_this.onGetUser()
				}).catch(err => {
					console.log(err)
				})
			},
			onGetUser(){
				let _this = this
				this.$request('/api2/get_self_info','POST',{}).then(res => {
					_this.valiFormData = res.data
					let img = JSON.parse(_this.valiFormData.image)
					_this.valiFormData.fileLists = []
					if(img.length){
						_this.valiFormData.fileLists = img.map(function(data){
							let obj = {url:data,name:data,extname:'png'}
							return obj
						})
					}
				}).catch(err => {
					console.log(err)
				})
			},
			onSelectImage(chooseImageRes){
				let _this = this
				const tempFilePaths = chooseImageRes.tempFilePaths;
				const api_url = _this.$func.api
				tempFilePaths.forEach((e) => {
					let fileurl = _this.$func.imgToBase64(e, base64 => {
						if (base64) {
							uni.uploadFile({
								url: api_url+'upload/WxAppOneLoad', //仅为示例，非真实的接口地址
								filePath: e,
								name: 'file',
								header:{
									'Content-Type':'multipart/form-data',
								},
								formData: {
									key: 'user',
									fileurl: base64,
									name: 'file',
								},
								success: (uploadFileRes) => {
									uploadFileRes.data = JSON.parse(uploadFileRes.data)
									let obj = {url:uploadFileRes.data.data,name:e,extname:'png'}
									_this.valiFormData.fileLists.push(obj)
								}
							});
						} else {
							console.error('转换失败');
						}
					});
				})
				
			},
			onDeleteImage(e){
				let arr = []
				this.valiFormData.fileLists.forEach(function(element) {
					if(element.name != e.tempFilePath){
						arr.push(element)
					}
				});
				this.valiFormData.fileLists = arr
			},
			imgToBase64(imagePath,type) {
				let _this = this
				const fileSystemManager = uni.getFileSystemManager();
				fileSystemManager.readFile({
					filePath: imagePath,
					encoding: 'base64',
					success: res => {
							
						if(type == 'avatar'){
							let fileurl = res.data
							_this.onUploadOneImg(fileurl)
							//执行上传方法
							return;
						}
						_this.images.push({name:imagePath,path:res.data})
					},
					fail: err => {
						callback(null);
					}
				});
			}
		}
	}
</script>

<style>
.head_img{width: 120px;border-radius: 120px;height: 120px;}
.user-image{width: 120px;height: 120px;border-radius: 120px;}
.grid{display: grid;grid-template-columns: 65% 35%;}
.getPhone{height: 37px;line-height: 37px;background-color: #FFD101;color: #333;border: 1px solid #FFD101;font-size: .8rem;}
</style>
